package com.rdxer.service;

import com.rdxer.api.para.UpdateQuestionPara;
import com.rdxer.core.utils.IdWorker;
import com.rdxer.model.Major;
import com.rdxer.model.Question;
import com.rdxer.model.QuestionOption;
import com.rdxer.repository.MajorRepository;
import com.rdxer.repository.QuestionOptionRepository;
import com.rdxer.repository.QuestionRepository;
import lombok.Data;
import lombok.Getter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Department 服务层
 */
@Service
@Data
@Getter
public class QuestionService implements CRUDPageServiceInterface<Question, String>  {


    @Autowired
    private QuestionRepository repository;

    @Autowired
    private IdWorker idWorker;



    @Autowired
    private QuestionOptionService optionService;


    List<QuestionOption> setupQuestionOption(String id, List<QuestionOption> ops){
        for (int i = 0; i < ops.size(); i++) {
            QuestionOption option = ops.get(i);
            option.setQuestionId(id);
            option.setIdx(i+1);
            optionService.save(option);
        }
        return ops;
    }

    public List<QuestionOption> loadOptions(String id) {
        return optionService.findAllByQuestionId(id);
    }

    public void update(UpdateQuestionPara questionPara) {
        // 更新题目信息模型
        Question q = new Question();
        BeanUtils.copyProperties(questionPara,q);
        repository.save(q);
        // 更新选项信息
        List<QuestionOption> all = optionService.findAllByQuestionId(questionPara.getId());
        optionService.deleteByIds(all.stream()
                .map(v->v.getId()).collect(Collectors.toList()));
        setupQuestionOption(questionPara.getId(),questionPara.getQuestionOptions());
    }
}
